package com.cyou.qb.face.aspect;

import java.util.Arrays;
import java.util.Date;

import javax.annotation.Resource;


import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import org.springframework.stereotype.Service;

import com.cyou.qb.face.entity.Face173AccessLog;
import com.cyou.qb.face.exception.QbGetDataException;
import com.cyou.qb.face.log.IOutServiceLog;
import com.cyou.qb.face.service.BaseFaceService;


/**
 * 173服务接口切面
 * 		负责处理：   1 运行方法后的日志记录
 * @author luzhaoman
 *
 */

@Aspect
@Service
public class FaceServiceAspect {

	private Logger logger = Logger.getLogger(FaceServiceAspect.class);

	@Resource(name="OutServiceFailLogImpl")
	private IOutServiceLog outServiceFailLog;

	public FaceServiceAspect(){
		super();
	}

	/**
	 * 增加aop切入点
	 */
	@Pointcut("execution(* com.cyou.qb.face.service.impl.*ServiceImpl.*(..))"+
			" || execution(* com.cyou.qb.face.service.mock.*.*(..))" )
	public void servicePointcut() {
	}

	/**  负责处理：   1 运行方法后的日志记录（Face173AccessLog）
	 * @param jp
	 * @throws Exception
	 *           
	 */
	@SuppressWarnings({"rawtypes" })
	@Around("servicePointcut()")
	public Object doAroundPointcut(ProceedingJoinPoint jp) throws Exception {

		String packageName = jp.getTarget().getClass().getPackage().getName();
		Class clazz = jp.getTarget().getClass();
		String className = clazz.getName().replaceAll(packageName + ".", "").split("\\$\\$")[0];
		String execution = jp.toShortString();
		String methodName = execution.substring(10, execution.length() - 1);
		if(methodName.indexOf("(")>=0){
			methodName=methodName.substring(0,methodName.indexOf("("));
		}
		String[] tmp = methodName.split("\\.");
		if(tmp.length==1){
			methodName=tmp[0];
		}else{
			methodName=tmp[tmp.length-1];
		}
		String method = className + "." + methodName;
		String param= Arrays.toString(jp.getArgs());
		if(param.length()>100){
			param=param.substring(0,100)+"..";
		}
		
		//初始化日志
		BaseFaceService service = (BaseFaceService) (jp.getTarget());
		Face173AccessLog accessLog = new Face173AccessLog();
		accessLog.setStartDate(new Date());
		accessLog.setMethod(method);
		accessLog.setMethodArgs(param);
		service.setAccessLog(accessLog);
		long start = System.currentTimeMillis();
		//运行方法
		Object result = null;
		try {
			result = jp.proceed();
			accessLog.setResult(true);
			accessLog.setEndDate(new Date());
			accessLog.setConsume(System.currentTimeMillis()-start);
			//运行方法后的日志记录
			try {
				outServiceFailLog.aspectLogProcess(accessLog);
			} catch (Exception e) {
				logger.error("error when log: " + method, new RuntimeException("持久化173接口日志出错", e));
			}
		} catch (Throwable e) {
			accessLog.setResult(false);
			logger.warn("service mothod: " + method + "\t param:" +param);
			accessLog.setEndDate(new Date());
			accessLog.setConsume(System.currentTimeMillis()-start);
			//运行方法后的日志记录
			try {
				outServiceFailLog.aspectLogProcess(accessLog);
			} catch (Exception ex) {
				logger.error("error when log: " + method, new RuntimeException("持久化173接口日志出错", ex));
			}
			throw new QbGetDataException(e.getMessage(),e);
		}
		
		return result;
	}
}
